package com.gaofei.file.controller;

import com.bw.springboot.starter.upload.model.Chunk;
import com.bw.springboot.starter.upload.service.FileService;
import com.bw.springboot.starter.upload.util.FileResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@CrossOrigin
@RestController
@Slf4j
public class FileController {
    @Autowired
    FileService fileService;

    /**
     * 大文件上传代码
     */

    @RequestMapping("bigupload")
    public String bigupload(@ModelAttribute Chunk chunk) throws InterruptedException {
        fileService.postFileUpload(chunk);
        if (chunk.getTotalChunks().equals(chunk.getChunkNumber())) {
            TimeUnit.SECONDS.sleep(2);
            FileResult fileResult = fileService.mergeFile(chunk);
            return "文件合并";
        }
        log.info("文件上传成功");
        return "success big!!!!";
    }

    /**
     * 普通的文件上传
     * @return
     */
    @RequestMapping("upload")
    public String upload(@RequestParam("myfile") MultipartFile file) throws IOException {
        //1.获取文件的名称--->QQ图片20231110083755.jpg
        String originalFilename = file.getOriginalFilename();
        //2.处理文件名-->目的:防止文件名称一样,被覆盖掉  uuid+.jpg
        String lastEx = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-","");
        //3.开始上传
        file.transferTo(new File("D:/upload/",uuid+lastEx));

        return "success!!!!";
    }
}
